<template>
  <div>
    <el-form ref="formRef" :model="form" label-width="120px" class="w-400px">
      <el-form-item label="姓名 :">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="头像 :">
        <div>
          <el-image
            :src="form.header_img"
            :zoom-rate="1.2"
            :preview-src-list="[form.header_img]"
            :initial-index="4"
            fit="cover"
          />
        </div>
        <div>
          <el-upload
            v-model:file-list="imgList"
            accept=".png, .jpg, .jpeg"
            class="mt-20px"
            :before-upload="beforeUpload"
            :on-remove="handleRemove"
            list-type="picture"
          >
            <el-button type="primary">点击上传图片</el-button>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import * as imageConversion from "image-conversion";
import { change_name_img, user } from "@/api/back/user";

const form = reactive({
  name: "张三",
  header_img: "",
});
const formRef = ref();
const imgList = ref([]);

const get_user = async () => {
  const {
    data: { name, header_img },
  } = await user();

  form.name = name;
  form.header_img = header_img;
};
get_user();

const submit = async () => {
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      const { code } = await change_name_img(form);
      if (code === 200) {
        ElMessage.success("修改成功！");
        get_user();
      } else {
        ElMessage.error("修改失败！");
      }
    }
  });
};

const toBase64 = (file) => {
  let reader = new FileReader();
  reader.onloadend = function () {
    imgList.value = [];
    form.header_img = reader.result;
    imgList.value.push({ name: "封面图片", url: form.header_img });
  };
  if (file) {
    reader.readAsDataURL(file);
  }
};

const beforeUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过2MB");
    return false;
  } else {
    const isSize = new Promise((resolve, reject) => {
      const _URL = window.URL || window.webkitURL;
      const img = new Image();
      img.onload = () => {
        const valid = true;
        valid ? resolve() : reject();
      };
      img.src = _URL.createObjectURL(file);
    }).then(
      () => {
        return file;
      },
      () => {
        ElMessage.error("上传图片大小不能超过2MB");
        return Promise.reject();
      }
    );
    isSize.then((file) => {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 < 100;
      if (!isJpgOrPng) {
        ElMessage.error("上传图片只能是 JPG 或 PNG 格式!");
        return false;
      }
      return new Promise((resolve) => {
        // 小于100KB 不压缩
        if (isLt2M) {
          resolve(file);
        }
        // 压缩到200KB,这里的200就是要压缩的大小,可自定义
        imageConversion.compressAccurately(file, 50).then((res: any) => {
          toBase64(res);
          resolve(res);
        });
      });
    });
  }
  return false; //取消自动上传
};

const handleRemove = (file) => {
  imgList.value = [];
  form.header_img = "";
};
</script>

<style scoped></style>
